<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolelist" border>
        <!-- 单列扩展 -->
        <el-table-column type="expand">
          <!-- 需要使用这一行信息的位置都需要用slot-scope给框住 -->
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <!-- <el-col :span="5"> -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  @close="removeRightById(scope.row,item1.id)"
                  closable
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="15">
                <!-- 通过for循环 嵌套渲染二级三级权限 二级三级在一行之中-->
                <el-row
                  :class="[i2!==0?'bdtop':'','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  closable
                >
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      @close="removeRightById(scope.row,item2.id)"
                      closable
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)"
                      closable
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" @click="showDialogTree(scope.row)" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户的对话框 -->
    <!-- <el-dialog title="权限分配" @close="editDialogClose" :visible.sync="editDialogVisible" width="30%"> -->
    <el-dialog title="权限分配" @close="rolesTreeDialogClose" :visible.sync="rightsTreeDialogVisible" width="30%">
      <!-- 内容主体区 -->
      <!-- tree用法  data为嵌套的list(tree型) props为具体显示循环方法 default-checked-keys默认勾选-->
      <!-- node-key每个树节点用来作为唯一标识的属性，整棵树应该是唯一的 -->
      <el-tree
        :data="roleTree"
        show-checkbox
        node-key="id"
        ref="roletreeRef"
        default-expand-all
        :default-checked-keys="defKeys"
        :props="roleTreeProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsTreeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleRightsDistribution">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //人物以及权限
      rolelist: [],
      //对话框是否显示？
      rightsTreeDialogVisible: false,
      //获取的权限树
      roleTree: [],
      //指定节点属性值
      roleTreeProps:{
          children:'children',
          label:'authName',
      },
      //默认选中的分配权限treenode
      defKeys:[116,105],
      //已经选中的结点
      roleNowId:''
    }
  },
//   默认选择项
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status != 200) {
        return this.message.error('获取角色列表失败')
      }
      this.rolelist = res.data
    },
    // tagremove操作 axios 1.5.7  第一个参数是为了刷新权限列表（这一行用户的id），第二个参数为该tag Id
    async removeRightById(aRow, tagId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        console.log(err)
      })
      if (confirmResult != 'confirm') {
        return this.$message.info('取消了删除')
      }
      //发送删除axios 并接受返回的参数
      const { data: res } = await this.$http.delete(
        'roles/' + aRow.id + '/rights/' + tagId
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除失败')
      }
      //只重新更新权限
      this.$message.success('删除成功')
      aRow.children = res.data
    },
    //分配权限点击事件
    async showDialogTree(aRow) {
      this.roleNowId=aRow.id
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsTreeDialogVisible = true
      if (res.meta.status != 200) {
        return this.$message.error('获取失败！')
      }
      this.roleTree = res.data
    //   console.log(res.data);
      let arr=[] //获取已经选择三级标签的id
      this.getCheckedId(aRow,arr)
      this.defKeys=arr
    },
    //获取已经选择的三级tag的id  (当前的角色（role）,填充进的数组) 递归方法 
    //数据格式参考1.4.1
    getCheckedId(role,arr){
        if(!role.children){
            arr.push(role.id)
            return
        }
        //将role中children循环
        role.children.forEach(item=>{
            this.getCheckedId(item,arr)
        })
    },
    //关闭权限分配框的事件
    rolesTreeDialogClose(){
        this.defKeys=[]
    },
    //1.5.6 将分配的权限发给后端
    async roleRightsDistribution(){
        // console.log(...this.$refs.roletreeRef.getCheckedNodes(false,true));
        
        
        const {data:res}=await this.$http.post(`roles/${this.roleNowId}/rights`,{
            rids:[...this.$refs.roletreeRef.getCheckedKeys(),...this.$refs.roletreeRef.getHalfCheckedKeys()].join(',')
        })
        console.log(res);
        
        if(res.meta.status!=200){
            return this.$message.error("权限分配失败！")
        }
        this.$message.success("权限分配成功")
        this.getRolesList()
        this.rightsTreeDialogVisible=false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
// 上边框
.bdtop {
  border-top: 1px solid #eee;
}
// 底边框
.bdbottom {
  border-bottom: 1px solid #eee;
}

//纵向居中对齐
.vcenter {
  display: flex;
  align-items: center;
}
</style>